package cn.schoolwow.flow.monitor.domain.handler;

import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.entity.FlowExecuteConfig;
import cn.schoolwow.quickdao.domain.database.dml.UpdateType;
import cn.schoolwow.quickflow.listener.FlowConfigRequestDataHandler;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class FlowMonitorFlowConfigMapHandler implements FlowConfigRequestDataHandler {
    @Autowired
    private FlowMonitorOption flowMonitorOption;

    @Override
    public Map<String, JSONObject> loadFlowConfigRequestDataMap() {
        List<FlowExecuteConfig> projectFlowConfigList = flowMonitorOption.dao.query(FlowExecuteConfig.class).execute().getList();
        Map<String,JSONObject> flowConfigMap = new HashMap<>();
        for(FlowExecuteConfig FlowExecuteConfig:projectFlowConfigList){
            flowConfigMap.put(FlowExecuteConfig.getName(), FlowExecuteConfig.getRequestData());
        }
        return flowConfigMap;
    }

    @Override
    public void saveFlowConfigRequestData(String categoryName, String flowName, JSONObject requestData) {
        FlowExecuteConfig FlowExecuteConfig = new FlowExecuteConfig();
        FlowExecuteConfig.setCategoryName(categoryName);
        FlowExecuteConfig.setName(flowName);
        FlowExecuteConfig.setRequestData(requestData);

        if(!flowMonitorOption.dao.exist(FlowExecuteConfig)){
            flowMonitorOption.dao.insert(FlowExecuteConfig);
        }
        JSONObject databaseRequestData = flowMonitorOption.dao.query(FlowExecuteConfig.class)
                .addQuery("name", FlowExecuteConfig.getName())
                .addColumn("requestData")
                .setColumnTypeMap("requestData", JSONObject.class)
                .execute()
                .getSingleColumn(JSONObject.class);
        putIncrementConfig(requestData, databaseRequestData);
        flowMonitorOption.dao.updateType(UpdateType.UpdateByUniqueKey).update(FlowExecuteConfig);
    }

    private void putIncrementConfig(JSONObject source, JSONObject target){
        if(null==target){
            return;
        }
        Set<String> keySet = source.keySet();
        for(String key:keySet){
            if(source.get(key) instanceof JSONObject){
                putIncrementConfig(source.getJSONObject(key), target.getJSONObject(key));
            }else if(target.containsKey(key)){
                source.put(key, target.get(key));
            }
        }
    }
}
